package com.frxuexi.video

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.alibaba.android.arouter.launcher.ARouter
import com.frxuexi.adapter.VideoAdapter
import com.frxuexi.lib_base.entity.VideoBeanItem
import com.frxuexi.lib_base.mvvm.BaseActivity
import com.frxuexi.video.databinding.ActivityVideoBinding
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

@AndroidEntryPoint
class VideoActivity : BaseActivity<ActivityVideoBinding,VideoViewModel>() {
    val videoAdapter by lazy { VideoAdapter() }
    var page=1
    override fun initData() {
        lifecycleScope.launch {
            vm.videoSuc.collect{
                if(!it.isNullOrEmpty()){
                    Log.i("===",it.toString())
                    videoAdapter.addData(it)
                    videoAdapter.notifyDataSetChanged()
                }
            }
        }
    }

    override fun initView() {
        binding.rvVideo.apply {
            adapter=videoAdapter
            layoutManager=StaggeredGridLayoutManager(2,RecyclerView.VERTICAL)
        }

        videoAdapter.setOnItemClickListener { adapter, view, position ->
            ARouter.getInstance().build("/video/VideoDetailActivity")
                .withSerializable("video",videoAdapter.data.get(position)).navigation()
        }
        vm.getVideos(page)

        binding.smart.setOnRefreshLoadMoreListener(object :OnRefreshLoadMoreListener{
            override fun onRefresh(refreshLayout: RefreshLayout) {
                page=1
                vm.getVideos(page)
                binding.smart.finishRefresh()
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                page++
                vm.getVideos(page)
                binding.smart.finishLoadMore()
            }

        })

        binding.etSearch.setOnClickListener {
            ARouter.getInstance().build("/video/SearchActivity").navigation()
        }

    }

}